package com.scoy.honeymei.activity.home;

import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.lzy.okgo.model.HttpParams;
import com.scoy.honeymei.R;
import com.scoy.honeymei.adapter.CheckTicketAdapter;
import com.scoy.honeymei.base.BaseActivity;
import com.scoy.honeymei.bean.CouponBean;
import com.scoy.honeymei.bean.TripSettleBean;
import com.scoy.honeymei.http.HpCallback;
import com.scoy.honeymei.http.HpGo;
import com.scoy.honeymei.url.MeConstant;
import com.scoy.honeymei.url.MyUrl;
import com.scoy.honeymei.utils.CheckUtil;
import com.scoy.honeymei.utils.IntentUtil;
import com.scoy.honeymei.utils.MyUtil;
import com.scoy.honeymei.utils.SPHelper;
import com.scoy.honeymei.utils.SystemUtil;
import com.scoy.honeymei.wxapi.PayEvent;
import com.scoy.honeymei.wxapi.PayUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ClassName: TripSettleActivity$
 * @Description: 出行结算
 * @Author: GaoZhan
 * @CreateDate: 2019/9/6/0006$ 上午 10:43$
 * @UpdateUser: 更新者
 * @UpdateDate: 2019/9/6/0006$ 上午 10:43$
 * @UpdateRemark: 更新内容
 */
public class TripSettleActivity extends BaseActivity {

    @BindView(R.id.back_iv)
    ImageView backIv;
    @BindView(R.id.title_tv)
    TextView titleTv;
    @BindView(R.id.sign_tv)
    TextView signTv;
    @BindView(R.id.title_llt)
    LinearLayout titleLlt;
    @BindView(R.id.sst_startadd_tv)
    TextView sstStartaddTv;
    @BindView(R.id.sst_jt_iv)
    ImageView sstJtIv;
    @BindView(R.id.sst_endadd_tv)
    TextView sstEndaddTv;
    @BindView(R.id.sst_tv4)
    TextView sstTv4;
    @BindView(R.id.sst_tv5)
    TextView sstTv5;
    @BindView(R.id.ct_subtract_tv)
    TextView ctSubtractTv;
    @BindView(R.id.ct_num_tv)
    TextView ctNumTv;
    @BindView(R.id.ct_add_tv)
    TextView ctAddTv;
    @BindView(R.id.sst_llt6)
    LinearLayout sstLlt6;
    @BindView(R.id.sst_tv3)
    TextView sstTv3;
    @BindView(R.id.sst_name_et)
    EditText sstNameEt;
    @BindView(R.id.sst_line)
    View sstLine;
    @BindView(R.id.sst_phone_et)
    EditText sstPhoneEt;
    @BindView(R.id.sst_tv2)
    TextView sstTv2;
    @BindView(R.id.sst_checkticket_tv)
    TextView sstCheckticketTv;
    @BindView(R.id.sst_tv0)
    TextView sstTv0;
    @BindView(R.id.sst_price_tv)
    TextView sstPriceTv;
    @BindView(R.id.sst_tv1)
    TextView sstTv1;
    @BindView(R.id.sst_totalprice_tv)
    TextView sstTotalpriceTv;
    @BindView(R.id.sst_allprice_tv)
    TextView sstAllpriceTv;
    @BindView(R.id.sst_buy_tv)
    TextView sstBuyTv;
    private TripSettleActivity mContext;
    private int trpId;
    private String payType = "null";
    private int couponId;
    private ArrayList<CouponBean> datacklist;
    private double shouldNum = 0.0;
    private int checkedPosition = -1;
    private double couponNum = 0.0;
    private String currentPrice;
    private int leftSeat;
    private String payThree;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settle_trip);
        ButterKnife.bind(this);
        mContext = TripSettleActivity.this;
        String num = getIntent().getStringExtra("num");
        String price = getIntent().getStringExtra("price");
        trpId = getIntent().getIntExtra("trpId", 0);
        leftSeat = getIntent().getIntExtra("leftSeat", 0);
        currentPrice = price;

        ctNumTv.setText(num);
        sstPriceTv.setText(price);

        setMoney();

        initNormal();

        httpTripSettle();

    }

    @Override
    public void initNormal() {
        datacklist = new ArrayList<>();

        titleTv.setText(R.string.Settlement);

        MyUtil.setStatusBar(mContext, getWindow(), true, R.color.colorWhite);
        titleLlt.setPadding(0, MyUtil.getStatusBarHeight(mContext), 0, 0);

        EventBus.getDefault().register(this);
    }

    @OnClick({R.id.back_iv, R.id.ct_subtract_tv, R.id.ct_add_tv, R.id.sst_checkticket_tv, R.id.sst_buy_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_iv:
                finish();
                break;
            case R.id.ct_subtract_tv:
                String sPrice = ctNumTv.getText().toString();
                int iSu = Integer.parseInt(sPrice);
                if (iSu > 1) {
                    ctNumTv.setText(iSu - 1 + "");
                } else {
                    MyUtil.mytoast(mContext, "不能再少了");
                }

                setMoney();
                break;
            case R.id.ct_add_tv:
                String sPrice0 = ctNumTv.getText().toString();
                int iSu0 = Integer.parseInt(sPrice0);
                if (iSu0 < leftSeat) {
                    ctNumTv.setText(iSu0 + 1 + "");
                    setMoney();
                }
                break;
            case R.id.sst_checkticket_tv:
                onCheck();
                break;
            case R.id.sst_buy_tv:
                if (TextUtils.isEmpty(sstNameEt.getText())) {
                    MyUtil.mytoast(mContext, "请输入姓名");
                    return;
                }
                if (TextUtils.isEmpty(sstPhoneEt.getText())) {
                    MyUtil.mytoast(mContext, "请输入手机号");
                    return;
                }
                if (!CheckUtil.isMobileNO(sstPhoneEt.getText().toString())) {
                    MyUtil.mytoast(mContext, "请输入正确手机号");
                    return;
                }

                if (Double.parseDouble(sstPriceTv.getText().toString()) * Integer.parseInt(ctNumTv.getText().toString()) < shouldNum) {
                    MyUtil.mytoast(mContext, "优惠券未达到使用要求，无法使用");
                    return;
                }
                showdialog();
                break;
        }
    }

    private void httpTripSettle() {
        HttpParams params = new HttpParams();
        params.put("travel_id", trpId);
        params.put("uid", SPHelper.getString(MeConstant.UID, ""));
        HpGo.newInstance().HttpGo(this, MyUrl.TRIP_TOBUY, params, new HpCallback() {
            @Override
            public void onSuccess(String o) {
                TripSettleBean tripSettleBean = new Gson().fromJson(o, TripSettleBean.class);
                payThree = tripSettleBean.getPaytype();
                sstStartaddTv.setText(tripSettleBean.getTravel_info().getStart_place());
                sstEndaddTv.setText(tripSettleBean.getTravel_info().getDestination());
                int pas_seat_num = tripSettleBean.getTravel_info().getPas_seat_num();
                if (pas_seat_num < 1) {
                    sstBuyTv.setEnabled(false);
                    sstBuyTv.setBackgroundResource(R.drawable.shape_gray_all5);
                    sstBuyTv.setText("已售罄");
                }
                List<CouponBean> coupon_list = tripSettleBean.getCoupon_list();
                if (coupon_list != null && coupon_list.size() > 0) {
                    sstCheckticketTv.setText("有可用优惠券");
                    datacklist.addAll(coupon_list);
                } else {
                    sstCheckticketTv.setText("无可用优惠券");
                    sstCheckticketTv.setEnabled(false);
                }

            }

            @Override
            public void onFailed(String code, String msg, String o) {
                MyUtil.mytoast(mContext, code + "," + msg);
            }

            @Override
            public void onError(int code, String errorMsg) {
                MyUtil.mytoast(mContext, errorMsg);
            }
        });

    }

    /**
     * 选择支付弹窗
     */
    private void showdialog() {
        final Dialog dialogpay = new Dialog(this, R.style.BottomDialogStyle);
        View view = View.inflate(this, R.layout.dialog_tocheckpay, null);

        ImageView imgClose = view.findViewById(R.id.imgClose);
        Button btnSure = view.findViewById(R.id.btnSure);
        TextView alipayTv = view.findViewById(R.id.txtZhifubao);
        TextView wxpayTv = view.findViewById(R.id.txtWechat);


        imgClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialogpay.dismiss();
            }
        });
        alipayTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alipayTv.setSelected(true);
                wxpayTv.setSelected(false);
                payType = "alipay";
            }
        });
        wxpayTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alipayTv.setSelected(false);
                wxpayTv.setSelected(true);
                payType = "wechat";
            }
        });
        dialogpay.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                payType = "null";
            }
        });


        btnSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!"null".equals(payType)) {
                    dialogpay.dismiss();
                    buyPay(payType);
                }
            }
        });

        dialogpay.setContentView(view);
        dialogpay.setCanceledOnTouchOutside(true);
        Window dialogWindow = dialogpay.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (SystemUtil.getScreenWidth(mContext));
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.BOTTOM;
        dialogWindow.setAttributes(lp);
        dialogpay.show();

    }

    private void buyPay(String payType) {
        HttpParams params = new HttpParams();
        params.put("name", sstNameEt.getText().toString().trim());
        params.put("mobile", sstPhoneEt.getText().toString().trim());
        params.put("coupon_id", couponId);
        params.put("travelid", trpId);
        params.put("num", ctNumTv.getText().toString());
        params.put("type", payType);
        params.put("uid", SPHelper.getString(MeConstant.UID, ""));
        HpGo.newInstance().HttpGo(this, MyUrl.TRIP_SETTLE, params, new HpCallback() {
            @Override
            public void onSuccess(String o) {
                // payThree  1  三方； 2  原生
                if ("2".equals(payThree)) {
                    if ("false".equals(o)) {
                        MyUtil.mytoast(mContext, "支付错误");
                        return;
                    }
                    PayUtil.toPayPayPay(mContext, payType, o);//支付
                } else {
                    if ("alipay".equals(payType)) {
                        IntentUtil.openAPP(mContext, MyUrl.APP_OPEN_ALIPAY + o);
                        finish();
                    } else {
                        if ("false".equals(o)) {
                            MyUtil.mytoast(mContext, "支付错误");
                            return;
                        }
                        PayUtil.toPayPayPay(mContext, payType, o);//支付
                        //  IntentUtil.openAPP(mContext, MyUrl.APP_OPEN_WX + o);
                    }

                }
            }

            @Override
            public void onFailed(String code, String msg, String o) {
                MyUtil.mytoast(mContext, code + "," + msg);
            }

            @Override
            public void onError(int code, String errorMsg) {
                MyUtil.mytoast(mContext, errorMsg);
            }
        });

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPayEvent(PayEvent event) {
        int type = event.getType();//0 成功 -1失败 -2取消
        if (type == 0) {
            MyUtil.mytoast0(mContext, "支付成功", R.mipmap.ic_sure);
            setResult(0x871);
            finish();
        } else if (type == -1) {
            MyUtil.mytoast(mContext, "支付失败");
        } else {
            MyUtil.mytoast(mContext, "支付取消");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    /**
     * 选择优惠券弹窗
     */
    public void onCheck() {
        final Dialog dialogcheck = new Dialog(mContext, R.style.BottomDialogStyle);
        View view = View.inflate(mContext, R.layout.dialog_check_ticket, null);
        TextView cancleTv = view.findViewById(R.id.cts_cancle_tv);
        TextView sureTv = view.findViewById(R.id.cts_sure_tv);
        RecyclerView dialogRv = view.findViewById(R.id.cts_rv);


        CheckTicketAdapter checkTicketAdapter = new CheckTicketAdapter(mContext, datacklist);
        dialogRv.setLayoutManager(new LinearLayoutManager(mContext, RecyclerView.VERTICAL, false));
        DividerItemDecoration did = new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL);
        did.setDrawable(getResources().getDrawable(R.drawable.divider_gray_line_pd));
        dialogRv.setAdapter(checkTicketAdapter);

        if (checkedPosition != -1) {
            checkTicketAdapter.setCheckedPosition(checkedPosition);
        }

        dialogcheck.setContentView(view);
        dialogcheck.setCanceledOnTouchOutside(true);
        Window dialogWindow = dialogcheck.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (SystemUtil.getScreenWidth(mContext));
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.BOTTOM;
        dialogWindow.setAttributes(lp);
        cancleTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialogcheck.dismiss();
            }
        });

        sureTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialogcheck.dismiss();
                checkedPosition = checkTicketAdapter.getCheckedPosition();
                if (checkedPosition != -1) {
                    CouponBean couponBean = datacklist.get(checkedPosition);
                    couponId = couponBean.getId();
                    shouldNum = Double.parseDouble(couponBean.getCondition());
                    sstCheckticketTv.setText(couponBean.getType_name() + "  满" + couponBean.getCondition() + "元优惠" + couponBean.getMoney() + "元");
                    couponNum = Double.parseDouble(couponBean.getMoney());
                } else {
                    couponId = 0;
                    shouldNum = 0.0;
                    couponNum = 0.0;
                    sstCheckticketTv.setText("不使用优惠券");
                }

                setMoney();
            }
        });

        dialogcheck.show();
    }

    private void setMoney() {
        String price = currentPrice;
        double vpAll = Double.parseDouble(price) * Integer.parseInt(ctNumTv.getText().toString())
                - couponNum;
        String sall = MyUtil.doubleTo2String(vpAll < 0 ? 0.0 : vpAll);
        sstTotalpriceTv.setText("￥" + sall);
        sstAllpriceTv.setText(sall);
    }

}
